<?php

// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
// 应用公共文件
/**
 *  ajax json 返回
 * @param type $status
 * @param type $msg
 * @param type $data
 * @return type array
 */
function js_return($status, $msg, $data = [], $count = 0)
{
    $obj         = new stdClass;
    $obj->status = $status;
    $obj->msg    = $msg;
    $obj->data   = $data;
    $obj->count  = $count;
    return json($obj);
}

/**
 * 获得当前时间
 *
 * @return string
 */
function T()
{
    return date("Y-m-d H:i:s");
}

/**
 *  获取随机数
 */
function get_secret_key()
{
    return mt_rand(100000, 999999);
}

function get_menus()
{
    if (empty(session('my_self')))
        exit;

    if (config('app_debug'))
    {
        $rules = new app\admin\model\Rules();
        return $rules->rules_to_menus(session('my_self')->rules);
    }
    else
    {
        return session('my_menus');
    }
}

function get_menus3()
{
    if (empty(session('my_self')))
        exit;

    if (config('app_debug'))
    {
        $rules = new app\admin\model\Rules();
        return $rules->rules_to_menus3(session('my_self')->rules);
    }
    else
    {
        return session('my_menus');
    }
}

function get_menus_frontend()
{
    if (empty(session('front_menus')))
        exit;

    if (config('app_debug'))
    {
        $rules = new app\index\model\Rules();
        return $rules->rules_to_menus(session('front_menus')->rules);
    }
    else
    {
        return session('front_menus');
    }
}

/*
 * 订单编号
 *  
 */

function get_codes()
{
    return date("YmdHis") . mt_rand(1000, 9999);
}

function get_code()
{
    $code = mt_rand(100000, 999999);
    return $code;
}

/**
 * 手机号验证
 * @param type $mobile
 * @return boolean
 */
function isMobile($mobile)
{
    if (!is_numeric($mobile))
    {
        return false;
    }
    return preg_match("/^0?1[3|4|5|6|7|8][0-9]\d{8}$/", $mobile) ? true : false;
}

/**
 * 检测是否手机登陆
 *
 * @return bool
 */
//function is_mobile() {
//    if (preg_match("/iphone|android/i", $_SERVER['HTTP_USER_AGENT'])) {
//        return true;
//    } else {
//        return false;
//    }
//}
/**
 * 生成唯一ID
 * @param type $a
 * @return type
 */
function unique($a)
{
    for
    (
    $a = md5($a, true),
    $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
    $d = '',
    $f = 0; $f < 8; $g = ord($a[$f]),
        $d .= $s[( $g ^ ord($a[$f + 8]) ) - $g & 0x1F],
        $f++
    )
        ;
    return strtolower($d);
}




//判断身份证是否准确
function is_idcard($id)
{
    $id        = strtoupper($id);
    $regx      = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";
    $arr_split = array();
    if (!preg_match($regx, $id))
    {
        return FALSE;
    }
    if (15 == strlen($id)) //检查15位 
    {
        $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";

        @preg_match($regx, $id, $arr_split);
        //检查生日日期是否正确 
        $dtm_birth = "19" . $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
        if (!strtotime($dtm_birth))
        {
            return FALSE;
        }
        else
        {
            return TRUE;
        }
    }
    else      //检查18位 
    {
        $regx      = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
        @preg_match($regx, $id, $arr_split);
        $dtm_birth = $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];
        if (!strtotime($dtm_birth)) //检查生日日期是否正确 
        {
            return FALSE;
        }
        else
        {
            //检验18位身份证的校验码是否正确。 
            //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。 
            $arr_int = array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            $arr_ch  = array('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2');
            $sign    = 0;
            for ($i = 0; $i < 17; $i++)
            {
                $b    = (int) $id{$i};
                $w    = $arr_int[$i];
                $sign += $b * $w;
            }
            $n       = $sign % 11;
            $val_num = $arr_ch[$n];
            if ($val_num != substr($id, 17, 1))
            {
                return FALSE;
            } //phpfensi.com 
            else
            {
                return TRUE;
            }
        }
    }
}

/**
 * 字符串截取函数
 *
 * @param string $sourcestr  字符串
 * @param int $cutlength     截取长度
 * @return string            返回字符串
 * @author lrenwang
 */
function a_cut($sourcestr, $cutlength)
{
    $returnstr = '';

    $i = 0;

    $n = 0;

    $str_length = strlen($sourcestr); //字符串的字节数

    $end = $cutlength * 2;

    while (($n < $end) and ( $i <= $str_length))
    {
        $temp_str = substr($sourcestr, $i, 1);
        $ascnum   = Ord($temp_str); //得到字符串中第$i位字符的ascii码
        if ($ascnum >= 224)
        { //如果ASCII位高与224，
            $returnstr = $returnstr . substr($sourcestr, $i, 3); //根据UTF-8编码规范，将3个连续的字符计为单个字符
            $i         = $i + 3; //实际Byte计为
            $n         = $n + 2; //字串长度计1
        }
        elseif ($ascnum >= 192)
        { //如果ASCII位高与192，
            $returnstr = $returnstr . substr($sourcestr, $i, 2); //根据UTF-8编码规范，将2个连续的字符计为单个字符
            $i         = $i + 2; //实际Byte计为2
            $n         = $n + 2; //字串长度计1
        }
        elseif ($ascnum >= 65 && $ascnum <= 90)
        { //如果是大写字母，
            $returnstr = $returnstr . substr($sourcestr, $i, 1);
            $i         = $i + 1; //实际的Byte数仍计1个
            if ($ascnum == 87)
            {
                $n = $n + 2;
            }
            else
            {
                $n = $n + 1.5; //但考虑整体美观，大写字母计成一个高位字符
            }
        }
        else
        { //其他情况下，包括小写字母和半角标点符号，
            $returnstr = $returnstr . substr($sourcestr, $i, 1);
            $i         = $i + 1; //实际的Byte数计1个
            if ($ascnum == 119)
            { //如果是几个特殊字 w
                $n = $n + 1.5;
            }
            else
            {
                $n = $n + 1; //小写字母和半角标点等与半个高位字符宽...
            }
        }
    }

    if ($str_length > $i)
    {
        $returnstr = $returnstr . "..."; //超过长度时在尾处加上省略号
    }
    return $returnstr;
}

/**
 * 测试变量输出
 *
 * @param string or array $str
 */
function P($data)
{
    echo "<pre>";
    if (is_array($data) || is_object($data))
        var_export($data);
    else
        echo $data;
    echo '</pre>';
    exit();
}

/**
 * 基本信息
 *
 * @param string or array $var
 * @return string or array
 * @example
 * 	config_info($info);
 */
function cfg($var = '')
{
    static $info = null;
    $file        = 'common/data/cfg.php';
    if ($info == null)
    {
        $file_info = file_get_contents($file);
        $info      = unserialize(str_replace('<?php exit;?>', '', $file_info));
    }

    //参数1是空 直接返回所有信息
    if ($var == '')
    {
        return $info;
    }
    if (is_array($var))
    {
        $info = array();
        foreach ($var as $k => $v)
        {
            $info[$k] = $v;
        }
        file_put_contents($file, '<?php exit;?>' . serialize($info));
        return true;
    }
    return isset($info[$var]) ? $info[$var] : '';
}

/**
 *  栏目类别树
 * 不能选择
 */
function menu_tree($list, $cid, $lock = 1, $id = '')
{
    $str       = '';
    $id_length = strlen($id);
    for ($i = 0; $i < $id_length; $i++)
    {
        if ($i == $id_length - 1)
        {
            $str .= '├';
        }
        else
        {
            $str .= '&nbsp;';
        }
    }
    foreach ($list as $v)
    {
        if (preg_match("~^{$id}\d{2}$~", $v['id']))
        {
            $selected = ($v['id'] == $cid) ? 'selected' : '';

            $node = ($v['node'] > 0 && $lock == 1 ) ? 'style="background-color:#ccc"  disabled="disabled"' : '';

            echo "<option value='{$v['id']}' {$selected} {$node} >{$str}{$v['name']}</option>";
            menu_tree($list, $cid, $lock, $v['id']);
        }
    }
}

/**
 *  栏目类别树
 * 可以选择
 */
function menu_trees($list, $cid, $lock = 1, $id = '')
{
    $str       = '';
    $id_length = strlen($id);
    for ($i = 0; $i < $id_length; $i++)
    {
        if ($i == $id_length - 1)
        {
            $str .= '├';
        }
        else
        {
            $str .= '&nbsp;';
        }
    }
    foreach ($list as $v)
    {
        if (preg_match("~^{$id}\d{2}$~", $v['id']))
        {
            $selected = ($v['id'] == $cid) ? 'selected' : '';

            echo "<option value='{$v['id']}' {$selected}  >{$str}{$v['name']}</option>";
            menu_tree($list, $cid, $lock, $v['id']);
        }
    }
}

/**
 * 类别类型
 *
 * @param string $key
 * @return string
 */
function category_type($key = null)
{
    $rs = array('text' => '文字列表', 'pic' => '图片列表');
    if ($key === null)
        return $rs;
    return $rs[$key];
}

/**
 * 充值类型
 *
 * @param string $key
 * @return string
 */
function recharge_type($key = null)
{
    $rs = array(1 => '商品', 2 => '代售');
    if ($key === null)
        return $rs;
    return $rs[$key];
}

/**
 * 订单类型
 *
 * @param string $key
 * @return string
 */
function cashorders_type($key = null)
{
    $rs = array(1 => '现金订单', 2 => '复购订单');
    if ($key === null)
        return $rs;
    return $rs[$key];
}

/**
 * 注册银行选项
 *
 * @param string $key
 * @return string
 */
function bank_lits($key = null)
{
    $rs = [1 => '中国银行', 2 => '中国工商银行', 3 => '中国农业银行', 4 => '中国建设银行'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

//通用 是否显示
function public_status($key = null)
{
    $rs = [1 => '正常', 2 => '隐藏'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

//通用 是否显示
function subsidy_type($key = null)
{
    $rs = [1 => '是', 2 => '否'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}


//通用 是否显示
function release_status($key = null)
{
    $rs = [1 => '草稿', 2 => '实行'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

//通用 是否显示
function sex_type($key = null)
{
    $rs = [1 => '男', 2 => '女'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

//计算总价
function sum_price($price, $number)
{
    $zongprice = $price * $number;
    return $zongprice;
}

function maintain_types($key = null)
{
    return \app\common\model\Maintains::maintain_types($key);
}

//前台会员订单算总价
function member_sum_price($code)
{
    $order     = new app\common\model\Orders();
    $rs        = $order->getShopAll("code = {$code}");
    $zongprice = 0;
    foreach ($rs as $v)
    {
        $zongprice += $v['totalmoney'];
    }
    return $zongprice;
}
function round_types($key=null)
{
    $rs = [
        'day' => '天',
        'week' => '周',
        'month' => '月',
        'year' => '年',
    ];
    if($key === null)
        return $rs;
    return $rs[$key];
}

/**
 * 公用下拉选择
 * $id 默认选中
 * $select选项数组
 */
function get_option($id, $select)
{
    $tmp = '';
    foreach ($select as $k => $v)
    {
        $selected = ( $id == $k) ? 'selected' : '';
        $tmp      .= "<option value='{$k}' {$selected} >{$v}</option> ";
    }
    return $tmp;
}

function get_option2($val, $select)
{
    $tmp = '';
    foreach ($select as $v)
    {
        $selected = ( $val == $v) ? 'selected' : '';
        $tmp      .= "<option value='{$v}' {$selected} >{$v}</option> ";
    }
    return $tmp;
}

/**
 * 公用单选
 */
function get_radio($id, $select, $name)
{
    $tmp = '';
    foreach ($select as $k => $v)
    {
        $checked = ( $id == $k) ? 'checked' : '';
        $tmp     .= "<input type='radio' lay-filter='{$name}' class='layui-form' name='{$name}' value='{$k}'  {$checked} title='{$v}' >";
    }
    return $tmp;
}

function get_radio_pic($pic,$select,$name)
{
    $tmp = '';
    foreach ($select as $v)
    {
        $checked = ( $pic == $v['pic']) ? 'checked' : '';
        $tmp     .= "<lable><input type='radio' lay-filter='{$name}' class='layui-form' name='{$name}' value='{$v['pic']}'  {$checked} title='<img width=40 height=40 src={$v['pic']}>' ></lable>";
    }
    return $tmp;

}

function get_extname($file)
{
    $fp       = fopen($file, "rb");
    $bin      = fread($fp, 2); //只读2字节
    fclose($fp);
    $bin_info = unpack("C2chars", $bin);
    $code     = intval($bin_info['chars1'] . $bin_info['chars2']);
    switch ($code)
    {
        case 7790:
            $type = 'exe';
            break;
        case 7784:
            $type = 'midi';
            break;
        case 8075:
            $type = 'zip';
            break;
        case 8297:
            $type = 'rar';
            break;
        case 255216:
            $type = 'jpg';
            break;
        case 7173:
            $type = 'gif';
            break;
        case 6677:
            $type = 'bmp';
            break;
        case 13780:
            $type = 'png';
            break;
        default:
            $type = $code;
            break;
    }
    return $type;
}

//shops  是否冻结
function shops_status($key = null)
{
    $rs = [1 => '正常', 2 => '冻结'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

//introduction 说明书头尾
function position_type($key = null){
    $rs = [1 => '前面', 2 => '后面'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

//maintains 维修状态
function maintains_status($key = null){
    $rs = ['关闭','待指派','待维修','待收款','完成'];
    if($key === null)
        return $rs;
    if($key>4 || $key<0)
        return '关闭';
    return $rs[$key];
}

//shops  是否冻结
function log_status($key = null)
{
    $rs = [1 => '登录', 2 => '操作'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

//shops  商家首页推荐
function hits_type($key = null)
{
    $rs = [0 => '未推荐', 1 => '已推荐'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

/*
 * 添加操作日志 
 * type 1登录 2操作
 * des 内容描述
 * uid 登录人id
 *  */
function add_log($type, $uid, $des)
{
    $Logs  = new app\admin\model\Logs();
    $Users = new app\admin\model\Users();
    $user  = $Users->getById($uid);
    $opt   = [
        'id'          => NULL,
        'uid'         => $user->id,
        'uname'       => $user->name,
        'type'        => $type,
        'status'      => 1,
        'ip'          => get_ip(),
        'description' => $des,
        'operat_ime'  => date("Y-m-d H:i:s"),
        'date'        => date("Y-m-d H:i:s"),
        'time'        => date("Y-m-d H:i:s"),
    ];
    $Logs->add($opt);
}

function add_maintain_log($des,$type = 1, $uid=null  )
{
    $Logs = new app\common\model\LogMaintains();
    if (empty($uid)) {
        $user = session('my_self');
    }
    else {
        $Users = new app\admin\model\Users();
        $user  = (Array)$Users->getById($uid);
    }
    $typearr = [1=>'修改',2=>'增加',3=>'删除'];
    $opt   = [
        'id'          => NULL,
        'uid'         => $user['id'],
        'uname'       => $user['name'],
        'type'        => $type,
        'status'      => 1,
        'ip'          => get_ip(),
        'description' => sprintf('%s(:%s) [%s]了 ', $user['name'], $user['id'], $typearr[$type]) . $des,
        'date'        => date("Y-m-d H:i:s"),
        'time'        => date("Y-m-d H:i:s"),
    ];
    $Logs->add($opt);
}

function add_clients_log($username,$type='',$des='')
{
    $Logs    = new app\common\model\LogClients();
    $Clients = new app\common\model\Clients();
    $client  = $Clients->_getWhere(['username'=>$username]);
    if($client){
    $opt     = [
        'id'            => NULL,
        'userid'        => $client->id,
        'username'      => $client->username,
        'ip'            => get_ip(),
        'des'           => $des,
        'type'          => $type,
        'create_at'     => T(),
    ];
    return $Logs->add($opt);
    }
    return false;
}

function get_ip()
{
    return $_SERVER['REMOTE_ADDR'];
}

function shop_type($key = null)
{
    $rs = [1 => '会员', 2 => '代理'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

function get_file_info($info)
{
    $file            = new stdClass();
    $file->name      = $info->getFileName();
    $file->path      = '/' . str_replace('\\', '/', $info->getPathName());
    $file->path_base = str_replace('\\', '/', $info->getPathName());
    $file->ext       = pathinfo($info->getFileName(), PATHINFO_EXTENSION);
    $file->size      = $info->getInfo()['size'];
    return $file;
}

//支付状态
function ispay_type($key = null)
{
    $rs = [1 => '未支付', 2 => '已支付'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

//发货状态
function issend_type($key = null)
{
    $rs = [1 => '未发货', 2 => '已发货'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

//操作人类别
function c_type($key = null)
{
    $rs = [1 => '会员', 2 => '后台管理员', 3 => '代理', 4 => '系统'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

//钱财出入
function trend_type($key = null)
{
    $rs = [1 => '收入', 2 => '支出'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

//钱财出入
function cashs_type($key = null)
{
    $rs = [1 => '会员充值', 2 => '后台充值', 3 => '服务费', 4 => '充值获得积分', 5 => '结算货款', 6 => '购买现金订单', 7 => '提现'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

function integrals_type($key = null)
{
    $rs = [1 => '积分消费', 2 => '商家盈利', 3 => '佣金', 4 => '充值获得积分', 5 => "购买积分", 6 => "出售积分", 7 => "退款返还"];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

//是否通过审核
function examine_status($key = null)
{
    $rs = [0 => '待审核', 1 => '已审核'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

//是否通过审核
function recharge_examine($key = null)
{
    $rs = [1 => '待审核', 2 => '已审核'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

//订单状态
function order_status($key = null)
{
    $rs = [1 => '待付款', 2 => '待发货', 3 => '申请退货', 4 => '已发货', 5 => '订单完成'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

/**
 * 发送短信
 * @param type $mobile  手机号
 * @param type $text    内容
 * @param type $subid   通道号码末尾添加的扩展号码
 * @return array
 */
function SmsSend($mobile, $text, $subid = '')
{
    $url    = 'http://115.28.112.245:8082/SendMT/SendMessage';
    $text   = urlencode($text);
    $params = 'UserName=' . config('app_smsUser') . '&UserPass=' . config('app_smsPwd') . '&subid=' . $subid . '&Mobile=' . $mobile . '&Content=' . $text;
    $ch     = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3);
    $data   = curl_exec($ch);
    curl_close($ch);
    if (empty($data))
    {
        return [
            'status' => 0,
            'text'   => urldecode($text),
            'rsId'   => '',
        ];
    }
    $data    = explode(',', $data);
    $data[0] = str_replace(PHP_EOL, '', $data[0]);
    $type    = ['00' => '多个手机号请求发送成功', '02' => 'IP限制', '03' => '单个手机号请求发送成功', '04' => '用户名错误', '05' => '密码错误', '06' => '编码错误', '08' => '参数错误', '09' => '手机号码有误', '10' => '扩展号码有误', '11' => '余额不足', '-1' => '服务器内部异常'];
    return [
        'status' => $data[0],
        'text'   => $type[$data[0]],
        'rsId'   => $data[1],
    ];
}

/**
 * 获取短信剩余条数
 * @return int
 */
function SmsNum()
{
    $url    = 'http://115.28.112.245:8082/SendMT/SearchStatus';
    $params = 'username=' . config('app_smsUser') . '&password=' . config('app_smsPwd');
    $ch     = curl_init();
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3);
    $data   = curl_exec($ch);
    curl_close($ch);
    return $data;
}

//object to array
function object2array(&$object)
{
    $object = json_decode(json_encode($object), true);
    return $object;
}

/**
 * @param $data array  要下载的数据
 * @param $title_arr array　表头
 * @param $filename string　文件名称
 */
function export_csv($data, $title_arr, $file_name = '')
{
    ini_set("max_execution_time", "3600");
    $csv_data = '';

    /** 标题 */
    $nums = count($title_arr);

    for ($i = 0; $i < $nums - 1; ++$i)
    {
        //$csv_data .= '"' . $title_arr[$i] . '",';
        $csv_data .= $title_arr[$i] . ',';
    }
    if ($nums > 0)
    {
        $csv_data .= $title_arr[$nums - 1] . "\r\n";
    }

    foreach ($data as $k => $row)
    {
        $_tmp_csv_data = '';
        foreach ($row as $key => $r)
        {
            $row[$key] = str_replace("\"", "\"\"", $r);

            if ($_tmp_csv_data == '')
            {
                $_tmp_csv_data = $row[$key];
            }
            else
            {
                $a             = $_tmp_csv_data .= ',' . $row[$key];
            }
        }
        $csv_data .= $_tmp_csv_data . "\r\n";
        unset($data[$k]);
    }

    $csv_data  = mb_convert_encoding($csv_data, "cp936", "UTF-8");
    $file_name = empty($file_name) ? date('Y-m-d-H-i-s', time()) : $file_name;
    // 解决IE浏览器输出中文名乱码的bug
    if (preg_match('/MSIE/i', $_SERVER['HTTP_USER_AGENT']))
    {
        $file_name = urlencode($file_name);
        $file_name = iconv('UTF-8', 'GBK//IGNORE', $file_name);
    }
    $file_name = $file_name . '.csv';
    header('Content-Type: application/download');
    header("Content-type:text/csv;");
    header("Content-Disposition:attachment;filename=" . $file_name);
    header('Cache-Control:must-revalidate,post-check=0,pre-check=0');
    header('Expires:0');
    header('Pragma:public');
    echo $csv_data;
    exit();
}

/**
 * 得到当前地址的参数  index?a=1&b=234&c=ggg
 * $vars 排除参数 例如'a' 或者'a,b'
 * $query url 默认是浏览器 url参数
 * $break 利用什么来分割默认是 '&'
 */
function get_query($vars = '', $query = '', $break = '&')
{
    $tmp   = '';
    $vars  = explode(',', $vars);
    if ($query == '')
        $query = explode('&', $_SERVER['QUERY_STRING']);
    foreach ($query as $v)
    {
        $arr = explode('=', $v);
        if (!preg_grep("/^{$arr[0]}$/", $vars))
        {
            if (!empty($arr[0]))
            {
                $tmp .= "{$arr[0]}={$arr[1]}{$break}";
            }
        }
    }
    return substr($tmp, 0, -1);
}

//评论数
function pinglun($id)
{
    $e   = new app\common\model\Evaluate();
    $num = count($e->getAll("shopid = {$id}"));
    return $num;
}

//总评分
function pingfen($id)
{
    $e    = new app\common\model\Evaluate();
    $num  = count($e->getAll("shopid = {$id}"));
    $ers  = $e->getAll("shopid = {$id}");
    $num2 = 0;
    foreach ($ers as $k => $v)
    {
        $num2 += $ers[$k]['commodity'];
    }
    if ($num2 != 0)
    {
        $pingfen = $num2 / $num;
        return number_format($pingfen, 2);
    }
    return $num2;
}

//销售量
function xiaoliang($id)
{
    $good = new app\common\model\Goods();
    $rs   = $good->getAll("shopid = {$id}");
    $num  = 0;
    foreach ($rs as $k => $v)
    {
        $num += $rs[$k]['sales_num'];
    }
    return $num;
}

function get_gift_num($vid, $sid)
{
    $num = 0;
    $rs  = Db::query("select sum(clicknum) as clicknum from  my_gifts where `vid` ='{$vid}' and `sid` ='{$sid}'");
    if (!empty($rs[0]['clicknum']))
    {
        $num = $rs[0]['clicknum'];
    }
    return $num;
}

function doctors_status($key = null)
{
    $rs = [1 => '未认证', 2 => '已认证'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

function patients_status($key = null)
{
    $rs = [1 => '待评估', 2 => '待设计', 3 => '待加工', 4 => '治疗中'];
    if ($key === null)
        return $rs;
    return $rs[$key];
}

function get_page()
{
    return get('page', 1);
}

/**
 * 分页函数
 * @author lrenwang
 *  1.1 增加url替换功能,默认是 '?page=#page' #page被替换成页数
 * 也可以这么调用 a_page(20,800,'/page/#page/')
 *
 *
 * @param int $rs    a_con()返回
 * @param string $url  url (扩展用)
 * @param int $offset  每页显示多少条
 * @return string
 */
function a_page2($rs, $url)
{
    $page   = $rs['page'];
    $count  = $rs['total'];
    $offset = $rs['size'];
    $page   = intval($page);
    if ($page < 1)
        $page   = 1;

    if ($url == '')
    {
        $url = '?page=#page';
    }
    //计算总页数
    $all = ceil($count / $offset);

    $href = str_replace('#page', '1', $url);
    $up   = "";
    //计算有没有上一页
    if ($page < 2)
    {
        $up .= "<a href='javascript:' style='cursor:not-allowed'>上一页</a>";
    }
    else
    {
        $href = str_replace('#page', $page - 1, $url);
        $up   .= "<a href='{$href}' >上一页</a>";
    }

    //计算有没有下一页
    if ($page < $all)
    {
        $down = str_replace('#page', $page + 1, $url);
        $down = "<a href='{$down}' >下一页</a>";
    }
    else
    {
        $down = "<a href='javascript:' style='cursor:not-allowed'>下一页</a>";
    }
    $href     = str_replace('#page', $all, $url);
    $down     .= "";
    $list     = '';
    $tiaojian = $all;
    $k        = 1;
    if ($all > 5)
    {
        if ($all > ($page + 3) && $page > 3)
        {
            $k        = $page - 3;
            $tiaojian = $page + 3;
            $list     .= "<a class='' href='javascript:;'>...</a>";
        }
        if ($page <= 3)
        {
            $tiaojian = $page + 3;
        }
        if ($all <= ($page + 3))
        {
            $list .= "<a class='' href='javascript:;'>...</a>";
            $k    = $page - 3;
        }
    }
    for ($s = $k; $s <= $tiaojian; $s++)
    {

        if ($s == $page)
        {
            $list .= "<a class='on' style='cursor:not-allowed'>{$s}</a>";
        }
        else
        {
            $c    = str_replace('#page', $s, $url);
            $list .= "<a class='' href='{$c}' >{$s}</a>";
        }
    }

    if ($all > 5)
    {
        if ($all > ($page + 3) && $page > 3)
        {
            $list .= "<a class='' href='javascript:;' >...</a>";
        }
        if ($page <= 3)
        {
            $list .= "<a class='' href='javascript:;' >...</a>";
        }
    }
    return "<div class='fyxg xs_fy'>
                {$up}{$list}{$down}
            </div>";
}

//获取文件名称和大小
function file_name_num($url, $type)
{
    $f = new app\admin\model\Files();
    if ($type == 1)
    {
        $name = $f->getByFileUrl($url);
        return $name['file_name'];
    }
    else
    {
        $num = $f->getByFileUrl($url);
        $size = $num['file_size'] / 1014;
        return round($size, 2);
    }
}


/**
 * 无限分类的排序
 */
function sortTree($arr, $i_name, $p_name, $p_start )
{
    $subs = array(); // 子孙数组
    foreach($arr as $v) {
        if($v[$p_name] == $p_start) {
            $subs[] = $v;
            $subs = array_merge($subs,sortTree($arr,$i_name,$p_name,$v[$i_name]));
        }
    }
    return $subs;
}


/**
 * 解析关系数据
 */
function menu2tree($arr, $selfKey, $parentKey, $parent = 0)
{
    $childs = [];
    foreach ($arr as $key => $val) {
        $sub = [];
        if ($val[$parentKey] == $parent) {
            $sub['id']         = $val[$selfKey];
            $sub['name']       = $val['name'];
            $sub['alias']      = '/' . config('admin_name') . '/' . $val['controller'] . '/' . $val['action'] . '/';
            $sub['controller'] = $val['controller'];
            $sub['action']     = $val['action'];
            $sub['pic']        = $val['pic'];
            $sub['childs']     = menu2tree($arr, $selfKey, $parentKey, $val[$selfKey]);
            $childs[]          = $sub;
        }
    }
    return $childs;
}

function menu_parent_ids($ids, $data)
{
    $pids = [];
    foreach ($data as $val){
        if(in_array($val['id'],$ids)){
            $pids[] = $val['pid'];
        }
    }
    if(empty($pids)){
        return [];
    }
    return array_unique(array_merge($pids,menu_parent_ids($pids,$data)));
}


/**
 * 解析关系数据
 */
function array2tree($arr, $selfKey, $parentKey, $name, $parent = 0)
{
    $childs = [];
    foreach ($arr as $key => $val) {
        $sub = [];
        if ($val[$parentKey] == $parent) {

            $sub['label']    = $sub['name'] = $val[$name];
            $sub['value']    = $sub['code'] = $val[$selfKey];
            $sub['disabled'] = !$sub['status'] = $val['status'];
            $sub['children'] = $sub['childs'] = array2tree($arr, $selfKey, $parentKey, $name, $val[$selfKey]);
            $sub['isLeaf']   = count($sub['childs']) == 0;
            $childs[]        = $sub;
        }
    }
    return $childs;
}

function tree_machine_types()
{
    $m = new \app\common\model\IconTypes();
    return $m->simpleTree();
}

function json_tree_machine_types()
{
    return json_encode(tree_machine_types());
}


/**
 * 获取当前时间格式
 * @return false|string
 */
function get_format_now(){
    return date("Y-m-d H:i:s");
}


/**
 *  栏目类别树
 * 不能选择
 */
function types_tree($list,$cid='',$disabled = false,$prefix = '&nbsp;&nbsp;|-- ')
{
    foreach ($list as $val) {

        $num = $val['pid'] ? substr_count($val['path'], '-') : 0;
        $str = str_repeat($prefix, $num);

        $node = empty($disabled) ?: 'style="background-color:#ccc"  disabled="disabled"';
        $selected = ($val['id'] == $cid) ? 'selected' : '';

        echo "<option value='{$val['id']}' {$selected} {$node} >{$str}{$val['name']}</option>";

    }
}

/**
 * @param $r
 * @param string $file
 * @return bool|int
 */
function print_to_file($r,$file='a.txt'){
    return file_put_contents($file,$r);
}


/**
 * 小程序获取用户信息
 * @param $js_code
 * @return mixed|string ['openid','session_key']
 */
function wx_get_key($js_code){

    if(empty($js_code)) return 'no js_code';

    $api_url = 'https://api.weixin.qq.com/sns/jscode2session';

    $postData = [
        'appid'=>config('wx_appid'),
        'secret'=>config('wx_appsecret'),
        'js_code'=>$js_code,
        'grant_type'=>'authorization_code'
    ];

    // init the resource
    $ch = curl_init();
    curl_setopt_array($ch, [
            CURLOPT_URL => $api_url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST => false,
            CURLOPT_POSTFIELDS => $postData
        ]);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

    $output = curl_exec($ch);

    if (curl_errno($ch)) {
        $output = '{"session_key":"","openid":"","error":"' . curl_error($ch) . '"}';
    }
    curl_close($ch);

    return json_decode($output,true);
}

/**
 * 返回是否正确签名
 * @param $signature
 * @param $rawData
 * @param $sessionKey
 * @return bool
 */
function wx_is_signature($signature,$rawData,$sessionKey){
    $sha = sha1($rawData . $sessionKey);
    return $signature == $sha;
}



function fetch_by_curl($url,$data,$method='GET')
{
    # code...
    //API URL
    $url;

    // init the resource
    $ch = curl_init();
    curl_setopt_array($ch, [
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POST => strtolower($method) == 'post' ? true : false,
        CURLOPT_POSTFIELDS => $data,
        CURLOPT_HTTPHEADER=>[
            'Content-Type'=>'application/json',
        ],
        //,CURLOPT_FOLLOWLOCATION => true,
    ]);


    //Ignore SSL certificate verification
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);


    //get response
    $output = curl_exec($ch);
    //Print error if any
    if (curl_errno($ch)) {
        return 'error:' . curl_error($ch);
    }

    curl_close($ch);

    return $output;
}

/**
 * 获取图片的Base64编码(不支持url)
 * @date 2017-02-20 19:41:22
 *
 * @param $img_file 传入本地图片地址
 *
 * @return string
 */
function imgToBase64($img_file) {

    $img_base64 = '';
    if (file_exists($img_file)) {
        $app_img_file = $img_file; // 图片路径
        $img_info = getimagesize($app_img_file); // 取得图片的大小，类型等

        //echo '<pre>' . print_r($img_info, true) . '</pre><br>';
        $fp = fopen($app_img_file, "r"); // 图片是否可读权限

        if ($fp) {
            $filesize = filesize($app_img_file);
            $content = fread($fp, $filesize);
            $file_content = chunk_split(base64_encode($content)); // base64编码
            switch ($img_info[2]) {           //判读图片类型
                case 1: $img_type = "gif";
                    break;
                case 2: $img_type = "jpg";
                    break;
                case 3: $img_type = "png";
                    break;
            }

            $img_base64 = 'data:image/' . $img_type . ';base64,' . $file_content;//合成图片的base64编码

        }
        fclose($fp);
    }

    return $img_base64; //返回图片的base64
}

/**
 * @param $data 遍历数据
 * @param $key
 * @param $eq
 * @param bool $val_key
 * @return string
 */
function get_options($data, $key, $eq, $text_key = false)
{
    $arr = array_map(function ($v) use ($eq, $key, $text_key) {
        $select = $eq == $v[$key] ? 'selected' : '';
        $text = $text_key ? $v[$text_key] : $v[$key];
        return "<option value='{$v[$key]}' {$select} >{$text}</option>";
    }, $data);

    return implode('', $arr);
}


function id2name($ids,$set)
{
    if (empty($ids))
        return '';
    $tmp   = [];
    foreach (explode(',', $ids) as $v)
    {
        if(isset($set[$v]))
        {
            $tmp[] = $set[$v];
        }
    }

    return implode(',', $tmp);
}

function province_data()
{
    $json = file_get_contents('./json/address_wxapp.json');
    $data = json_decode($json, true);
    $keys = $values = [];
    foreach ($data as $val) {
        $keys[]   = $val['value'];
        $values[] = $val['short_name'];
    }
    return array_combine($keys, $values);
}

/**
 * 获取统计数据以key
 */
function data_statistic($keyValue, $column, $data)
{
    $datas  = array_map(function ($val) use ($column) {
        return $val[$column];
    }, $data);
    $counts = array_count_values($datas);
    $d      = [];
    foreach ($keyValue as $key => $val) {
        $d[] = ['name' => $val, 'value' => isset($counts[$key]) ? $counts[$key] : 0,];
    }
    return $d;
}

/**
 * 获取统计数据以value
 */
function data_statistic_value($keyValue,$column,$data)
{

    $datas  = array_map(function ($val) use ($column) {
        return $val[$column];
    }, $data);
    $counts = array_count_values($datas);
    $d = [];
    foreach ($keyValue as $key=>$val){
        $d[] = ['name' => $val, 'value' => isset($counts[$val]) ? $counts[$val] : 0,];
    }
}

function num_percent($source,$divide,$point=2)
{
    return round(100 * $source/$divide, $point);
}

/**
 * Convert a numeric string from base 10 to another base.
 *
 * @param $value  decimal string
 * @param int $b  base , max is 62
 * @return string
 */
function decimal_to_base($value, $b = 62)
{
    $base   = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $r      = $value % $b;
    $result = $base[$r];
    $q      = floor($value / $b);

    while ($q) {
        $r      = $q % $b;
        $q      = floor($q / $b);
        $result = $base[$r] . $result;
    }
    return $result;
}


function base_to_decimal($value, $b = 62)
{
    $base = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $len  = strlen($value);
    $num  = 0;
    for ($n = $len - 1, $i = 0; $n >= 0; $n--, $i++) {
        $num += strpos($base, $value[$i]) * pow($b, $n);
    }
    return $num;
}


function mro_get($key=null)
{
    try{
        $json = file_get_contents('./json/mro.json');
    }catch (Exception $e){
        $json = [];
        file_put_contents('./json/mro.json','{}');
    }
    $data = empty($json) ? [] : json_decode($json,true);
    if($key === null)
        return $data;
    return $data[$key];
}

function mro_set($key,$val)
{
    $data = mro_get();
    $data[$key] = $val;
    return file_put_contents('./json/mro.json',json_encode($data));
}

function table_key_value($model,$filter=null){
    $m = new $model();
    $data = [];
    $fetchData = $m->where($filter)->select();
    foreach ($fetchData as $val){
        $data[$val['id']] = $val['name'];
    }
    return $data;
}



/**
 * @desc 过滤出允许字段
 * @param array/string $fields
 * @return array
 */
function input_db_allowed($fields,$raw=[]){

    if(is_string($fields))
        $fields = explode(',',$fields);

    $input = input();
    $data = array_merge($raw,[]);

    foreach ($input as $key=>$val) {
        if(in_array($key,$fields))
            $data[$key]=$val;
    }
    return $data;
}


function my_icontypes($uid=null)
{
    $where = ' 1 ';
    $field = 'id,id as code,name,mode,pic,color';
    if($uid){
        $m = new \app\admin\model\Users();
        $user = $m->getById($uid);
        $where .= " and id in ({$user->icontypes}) ";
    }
    $m             = new \app\common\model\IconTypes();
    return $m->field($field)->where($where)->select();
}

function compute_centerpoint($points)
{
    $points = explode(',', $points);
    $lngs   = array_filter($points, function ($k) {
        return $k % 2 == 0;
    }, ARRAY_FILTER_USE_KEY);
    $lats   = array_filter($points, function ($k) {
        return $k % 2 == 1;
    }, ARRAY_FILTER_USE_KEY);
    $num    = count($lngs);
    return json_encode([array_sum($lngs) / $num, array_sum($lats) / $num]);
}


function get_uniqueid($id)
{
    if (!function_exists('gen10')) {
        function gen10($value, $b = 10)
        {
            $base   = '8950761234';
            $r      = $value % $b;
            $result = $base[$r];
            $q      = floor($value / $b);

            while ($q) {
                $r      = $q % $b;
                $q      = floor($q / $b);
                $result = $base[$r] . $result;
            }
            return $result;
        }
    }
    if (!function_exists('gen36')) {
        function gen36($value, $b = 36)
        {
            $base   = 'V8BKS4TMQ2YLFNW7R1Z0I3GEJH6C5OAD9UPX';
            $r      = $value % $b;
            $result = $base[$r];
            $q      = floor($value / $b);

            while ($q) {
                $r      = $q % $b;
                $q      = floor($q / $b);
                $result = $base[$r] . $result;
            }
            return $result;
        }
    }

    // 月 + id 生成的唯一码
    return str_pad(gen10(date('n')), 2, gen10(0), STR_PAD_LEFT)
        . str_pad(gen36($id), 5, gen36(0), STR_PAD_LEFT);
}

/**
 * 存储数据
 */
function influx_save($data,$tags){

    $database = \InfluxDB\Client::fromDSN(
        sprintf('influxdb://%s:%s@%s:%s/%s',
            config('app.influx_username'),
            config('app.influx_password'),
            config('app.influx_host'),
            config('app.influx_port'),
            config('app.influx_db')));
    $client = $database->getClient();
    $db = $client->selectDB(config('app.influx_db'));

    $points = array_map(function ($val) use($tags) {
        return new \InfluxDB\Point('temperatures',
            $val['temperature'],
            $tags,
            [],
            time()
        );
    }, $data);
//
    $result = $db->writePoints($points, \InfluxDB\Database::PRECISION_SECONDS);
    return $result;

//    return $result;
//        echo dump($result);
//        $lastQuery = $client->getLastQuery();
//        echo $lastQuery . '<br />';


//        $result2 = $database->query("select *  from temperatures WHERE userid='2' LIMIT 10");

//        $points2 = $result2->getPoints();
//
//        $lastQuery = $client->getLastQuery();
//        echo $lastQuery . '<br />';
//        dump($points2);
}

// 查询数据
function influx_get($where, $limit=20){
    $database = \InfluxDB\Client::fromDSN(
        sprintf('influxdb://%s:%s@%s:%s/%s',
            config('app.influx_username'),
            config('app.influx_password'),
            config('app.influx_host'),
            config('app.influx_port'),
            config('app.influx_db')));
    $client = $database->getClient();
//    $db = $client->selectDB(config('app.influx_db'));

    $whereCon = 'TRUE';
    foreach ($where as $key=>$val){
        $whereCon .= " AND {$key}='{$val}'";
    }

    $query = "select * from temperatures WHERE {$whereCon} LIMIT {$limit}";

    $result = $database->query($query);

    $points = $result->getPoints();

    empty($points) && die($client->getLastQuery());

    return $points;
}

function randstr($length)
{
    $hash = '';
    $chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz';
    $max = strlen($chars) - 1;
    mt_srand((double)microtime() * 1000000);
    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}
